import sys
import time
import logging
import struct
import threading
from smap.driver import SmapDriver
from smap.loader import SmapLoadError
from smap.util import periodicSequentialCall
import MySQLdb
import datetime, calendar
from twisted.internet import threads, reactor

class dustV1LiveDriver(SmapDriver):
    def setup(self, opts):
        #create all the data streams (m1c1, m1c2, m2c1, m2c2, etc)
        self.ids = {}
        self.calibrations = {}
        for motename in xrange(17, 93):
            t1 = self.add_timeseries('/m%i/c1' % motename, opts.get('units_m%ic1' % motename, 'dF'), data_type="double")
            t2 = self.add_timeseries('/m%i/c2' % motename, opts.get('units_m%ic2' % motename, 'dF'), data_type="double")
            self.ids[motename] = (t1['uuid'], t2['uuid'])
            calFactor1 = float(opts.get("calFactor_m%ic1" % motename, '.852674'))
            calConstant1 = float(opts.get("calConstant_m%ic1" % motename, '9.817803'))
            calFactor2 = float(opts.get("calFactor_m%ic2" % motename, '.990099'))
            calConstant2 = float(opts.get("calConstant_m%ic2" % motename, '-.44881'))
            self.calibrations[motename] = (calFactor1, calConstant1, calFactor2, calConstant2)
        self.period = opts.get("Period", 90)
            
    def read(self):
        self.con = MySQLdb.connect (host = '192.168.1.30', port = 3306, user = 'facsuser', passwd = 'fcllc00', db = 'facsdb')
        self.cursor = self.con.cursor()        
        self.cursor.execute ("SELECT moteid,data.A1,data.A2,datetime_stamp FROM data join motes on data.mac = motes.mac order by datetime_stamp desc limit 100;")
        data = self.cursor.fetchall()
        for row in data:
            motename = int(row[0])
            channel1 = row[1]
            channel2 = row[2]
            motetime = calendar.timegm(row[3].utctimetuple()) #this assumes that you have set your timezone to UTC (London)
            self.add(self.ids[motename][0], motetime, channel1*self.calibrations[motename][0]+self.calibrations[motename][1])
            self.add(self.ids[motename][1], motetime, channel2*self.calibrations[motename][2]+self.calibrations[motename][3])
        self.cursor.close()

    def start(self):
        periodicSequentialCall(self.read).start(self.period)
